#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QTextEdit>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    ,edit(nullptr)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_actionnew_triggered()
{
    //
    if(edit!=nullptr){
        int ret=QMessageBox::warning(this,"提示","是否覆盖？",QMessageBox::Yes,QMessageBox::No);
        if(ret==QMessageBox::Yes){
            delete edit;
            edit=nullptr;
        }else{
            QString filename=QFileDialog::getSaveFileName(this);
            QFile file(filename);
            file.open(QIODevice::WriteOnly);
            file.write(edit->toPlainText().toUtf8());
            file.close();
        }
        edit=new QTextEdit(this);
        this->setCentralWidget(edit);
    }
    edit=new QTextEdit(this);
    this->setCentralWidget(edit);
}

void MainWindow::on_actionopen_triggered()
{
    QString filename=QFileDialog::getOpenFileName(this);
    savefilename=filename;
    QFile file(filename);
    file.open(QIODevice::ReadOnly);
    QString data=file.readAll();//小文件
//    QString data=file.read();
    file.close();
    if(edit==nullptr){
        edit=new QTextEdit(this);
        this->setCentralWidget(edit);
    }
    edit->setText(data);
}

void MainWindow::on_actionsave_triggered()
{
    if(savefilename.isEmpty()){
        savefilename=QFileDialog::getSaveFileName(this);
    }
    QFile file(savefilename);
    file.open(QIODevice::WriteOnly);
    if(edit==nullptr){
        edit=new QTextEdit(this);
        this->setCentralWidget(edit);
    }
    file.write(edit->toPlainText().toUtf8());
    file.close();
}

void MainWindow::on_actionsave_as_triggered()
{
    QString filename=QFileDialog::getOpenFileName(this);
    QFile file(filename);
    file.open(QIODevice::WriteOnly);
    if(edit==nullptr){
        edit=new QTextEdit(this);
        this->setCentralWidget(edit);
    }
    file.write(edit->toPlainText().toUtf8());
    file.close();
}

void MainWindow::on_actionexit_triggered()
{
    this->close();
}
